
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Tathata.Common.BLL.Entities;
using Tathata.Common.BLL.Managers;
using Tathata.Common.Utils;
using System.Collections.Generic;
using Tathata.Common.BLL.EntityCollections;
using Tathata.Common.BLL.Enums;
using Tathata.Web.Administration.Modules;

namespace Tathata.Web.Administration
{
    public partial class Administration_ProductVariantDetails : BaseNopAdministrationPage
    {
        private void BindData()
        {
            ProductVariant productVariant = ProductVariantManager.GetByProductVariantID(this.ProductVariantID);
            if (productVariant != null)
            {
                Product product = productVariant.Product;
                if (product == null)
                    Response.Redirect("Products.aspx");
                lblProductName.Text = Server.HtmlEncode(product.Name);
                hlProductURL.NavigateUrl = "ProductDetails.aspx?ProductID=" + product.ProductID;

                this.txtName.Text = productVariant.Name;
                this.txtSKU.Text = productVariant.SKU;
                this.txtDescription.Value = productVariant.Description;
                this.txtAdminComment.Text = productVariant.AdminComment;
                this.txtManufacturerPartNumber.Text = productVariant.ManufacturerPartNumber;
                this.cbIsDownload.Checked = productVariant.IsDownload;

                Download productVariantDownload = productVariant.Download;
                if (productVariantDownload != null)
                {
                    btnRemoveProductVariantDownload.Visible =true;
                    hlProductVariantDownload.Visible = true;
                    string adminDownloadUrl = DownloadManager.GetAdminDownloadUrl(productVariantDownload);
                    hlProductVariantDownload.NavigateUrl = adminDownloadUrl;
                }
                else
                {
                    btnRemoveProductVariantDownload.Visible = false;
                    hlProductVariantDownload.Visible = false;
                }
                this.cbIsShipEnabled.Checked = productVariant.IsShipEnabled;
                this.cbIsFreeShipping.Checked = productVariant.IsFreeShipping;
                CommonHelper.SelectListItem(this.ddlTaxCategory, productVariant.TaxCategoryID);
                this.txtStockQuantity.Value = productVariant.StockQuantity;
                CommonHelper.SelectListItem(this.ddlWarehouse, productVariant.WarehouseId);
                this.cbDisableBuyButton.Checked = productVariant.DisableBuyButton;
                this.cbRequiresTextOption.Checked = productVariant.RequiresTextOption;
                this.txtTextOptionPrompt.Text = productVariant.TextOptionPrompt;
                this.txtPrice.Value = productVariant.Price;
                this.txtOldPrice.Value = productVariant.OldPrice;
                this.txtWeight.Value = productVariant.Weight;
                this.txtLength.Value = productVariant.Length;
                this.txtWidth.Value = productVariant.Width;
                this.txtHeight.Value = productVariant.Height;

                Picture productVariantPicture = productVariant.Picture;
                btnRemoveProductVariantImage.Visible = productVariantPicture != null;
                string pictureUrl = PictureManager.GetPictureUrl(productVariantPicture, 100, 80);
                this.iProductVariantPicture.ImageUrl = pictureUrl;

                this.cbPublished.Checked = productVariant.Published;
                this.txtDisplayOrder.Value = productVariant.DisplayOrder;

                BindProductVariantAttributes();

                DiscountCollection discountCollection = productVariant.Discounts;
                List<int> _discountIDs = new List<int>();
                foreach (Discount dis in discountCollection)
                    _discountIDs.Add(dis.DiscountID);
                DiscountMappingControl.SelectedDiscountIDs = _discountIDs;
                DiscountMappingControl.BindData();
            }
            else
                Response.Redirect("Products.aspx");
        }

        private void BindProductVariantAttributes()
        {
            ProductVariantAttributeCollection productVariantAttributes = ProductVariantAttributeManager.GetAllByProductVariantID(this.ProductVariantID);
            if (productVariantAttributes.Count > 0)
            {
                gvProductVariantAttributes.Visible = true;
                gvProductVariantAttributes.DataSource = productVariantAttributes;
                gvProductVariantAttributes.DataBind();
            }
            else
                gvProductVariantAttributes.Visible = false;
        }

        private void FillDropDowns()
        {
            this.ddlTaxCategory.Items.Clear();
            ListItem itemTaxCategory = new ListItem("Not Taxable", "0");
            this.ddlTaxCategory.Items.Add(itemTaxCategory);
            TaxCategoryCollection taxCategoryCollection = TaxCategoryManager.GetAllTaxCategories();
            foreach (TaxCategory taxCategory in taxCategoryCollection)
            {
                ListItem item2 = new ListItem(taxCategory.Name, taxCategory.TaxCategoryID.ToString());
                this.ddlTaxCategory.Items.Add(item2);
            }

            this.ddlWarehouse.Items.Clear();
            ListItem itemWarehouse = new ListItem("---", "0");
            this.ddlWarehouse.Items.Add(itemWarehouse);
            WarehouseCollection warehouseCollection = WarehouseManager.GetAllWarehouses();
            foreach (Warehouse warehouse in warehouseCollection)
            {
                ListItem item2 = new ListItem(warehouse.Name, warehouse.WarehouseID.ToString());
                this.ddlWarehouse.Items.Add(item2);
            }

            this.ddlNewProductAttributes.Items.Clear();
            ProductAttributeCollection productAttributes = ProductAttributeManager.GetAllProductAttributes();
            foreach (ProductAttribute pa in productAttributes)
            {
                ListItem item2 = new ListItem(pa.Name, pa.ProductAttributeID.ToString());
                this.ddlNewProductAttributes.Items.Add(item2);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.FillDropDowns();
                this.BindData();
            }
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    ProductVariant productVariant = ProductVariantManager.GetByProductVariantID(ProductVariantID);
                    if (productVariant != null)
                    {
                        Picture productVariantPicture = productVariant.Picture;
                        HttpPostedFile productVariantPictureFile = fuProductVariantPicture.PostedFile;
                        if ((productVariantPictureFile != null) && (!String.IsNullOrEmpty(productVariantPictureFile.FileName)))
                        {
                            byte[] productVariantPictureBinary = PictureManager.GetPictureBits(productVariantPictureFile.InputStream, productVariantPictureFile.ContentLength);
                            if (productVariantPicture != null)
                                productVariantPicture = PictureManager.UpdatePicture(productVariantPicture.PictureID, productVariantPictureBinary, productVariantPictureFile.ContentType, true);
                            else
                                productVariantPicture = PictureManager.InsertPicture(productVariantPictureBinary, productVariantPictureFile.ContentType, true);
                        }
                        int productVariantPictureID = 0;
                        if (productVariantPicture != null)
                            productVariantPictureID = productVariantPicture.PictureID;

                        Download productVariantDownload = productVariant.Download;
                        HttpPostedFile productVariantDownloadFile = fuProductVariantDownload.PostedFile;
                        if ((productVariantDownloadFile != null) && (!String.IsNullOrEmpty(productVariantDownloadFile.FileName)))
                        {
                            byte[] productVariantDownloadBinary = DownloadManager.GetDownloadBits(productVariantDownloadFile.InputStream, productVariantDownloadFile.ContentLength);
                            if (productVariantDownload != null)
                                productVariantDownload = DownloadManager.UpdateDownload(productVariantDownload.DownloadID, productVariantDownloadBinary, productVariantDownloadFile.ContentType, true);
                            else
                                productVariantDownload = DownloadManager.InsertDownload(productVariantDownloadBinary, productVariantDownloadFile.ContentType, true);
                        }
                        int productVariantDownloadID = 0;
                        if (productVariantDownload != null)
                            productVariantDownloadID = productVariantDownload.DownloadID;

                        productVariant = ProductVariantManager.UpdateProductVariant(ProductVariantID, productVariant.ProductID,
                             txtName.Text, txtSKU.Text, txtDescription.Value, txtAdminComment.Text, txtManufacturerPartNumber.Text,
                             cbIsDownload.Checked, productVariantDownloadID, cbIsShipEnabled.Checked, cbIsFreeShipping.Checked,
                             int.Parse(this.ddlTaxCategory.SelectedItem.Value), txtStockQuantity.Value,
                             int.Parse(this.ddlWarehouse.SelectedItem.Value),cbDisableBuyButton.Checked,
                             cbRequiresTextOption.Checked, txtTextOptionPrompt.Text,
                             txtPrice.Value, txtOldPrice.Value, txtWeight.Value, txtLength.Value,
                             txtWidth.Value, txtHeight.Value, productVariantPictureID, cbPublished.Checked,
                             productVariant.Deleted, txtDisplayOrder.Value, productVariant.CreatedOn, DateTime.Now);

                        foreach (Discount discount in DiscountManager.GetDiscountsByProductVariantID(productVariant.ProductVariantID))
                            DiscountManager.RemoveDiscountFromProductVariant(productVariant.ProductVariantID, discount.DiscountID);
                        foreach (int discountID in DiscountMappingControl.SelectedDiscountIDs)
                            DiscountManager.AddDiscountToProductVariant(productVariant.ProductVariantID, discountID);

                        Response.Redirect("ProductVariantDetails.aspx?ProductVariantID=" + productVariant.ProductVariantID);
                    }
                    else
                        Response.Redirect("Products.aspx");
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }
        }

        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            try
            {
                ProductVariantManager.MarkProductVariantAsDeleted(this.ProductVariantID);
                Response.Redirect("Products.aspx");
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }
       
        protected void btnRemoveProductVariantImage_Click(object sender, EventArgs e)
        {
            try
            {
                ProductVariant productVariant = ProductVariantManager.GetByProductVariantID(this.ProductVariantID);
                if (productVariant != null)
                {
                    PictureManager.DeletePicture(productVariant.PictureID);
                    ProductVariantManager.RemoveProductVariantPicture(productVariant.ProductVariantID);
                    BindData();
                }
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }

        protected void btnRemoveProductVariantDownload_Click(object sender, EventArgs e)
        {
            try
            {
                ProductVariant productVariant = ProductVariantManager.GetByProductVariantID(this.ProductVariantID);
                if (productVariant != null)
                {
                    DownloadManager.DeleteDownload(productVariant.DownloadID);
                    ProductVariantManager.RemoveProductVariantDownload(productVariant.ProductVariantID);
                    BindData();
                }
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }

        protected void btnNewProductVariantAttribute_Click(object sender, EventArgs e)
        {
            try
            {
                ProductVariant productVariant = ProductVariantManager.GetByProductVariantID(this.ProductVariantID);
                if (productVariant != null)
                {
                    int productAttributeID = int.Parse(ddlNewProductAttributes.SelectedItem.Value);

                    ProductVariantAttribute productVariantAttribute = ProductVariantAttributeManager.InsertProductVariantAttribute(productVariant.ProductVariantID,
                        productAttributeID, cbNewProductVariantAttributeIsRequired.Checked, txtNewProductVariantAttributeDisplayOrder.Value);

                    BindProductVariantAttributes();
                }
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }

        protected void gvProductVariantAttributes_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "UpdateProductVariantAttribute")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = gvProductVariantAttributes.Rows[index];

                HiddenField hfProductVariantAttributeID = row.FindControl("hfProductVariantAttributeID") as HiddenField;
                DropDownList ddlProductAttribute = row.FindControl("ddlProductAttribute") as DropDownList;
                CheckBox cbIsRequired = row.FindControl("cbIsRequired") as CheckBox;
                NumericTextBox txtDisplayOrder = row.FindControl("txtDisplayOrder") as NumericTextBox;

                int productVariantAttributeID = int.Parse(hfProductVariantAttributeID.Value);
                int productAttributeID = int.Parse(ddlProductAttribute.SelectedItem.Value);
                int displayOrder = txtDisplayOrder.Value;

                ProductVariantAttribute productVariantAttribute = ProductVariantAttributeManager.GetByProductVariantAttributeID(productVariantAttributeID);

                if (productVariantAttribute != null)
                    ProductVariantAttributeManager.UpdateProductVariantAttribute(productVariantAttribute.ProductVariantAttributeID,
                       productVariantAttribute.ProductVariantID, productAttributeID,
                       cbIsRequired.Checked, displayOrder);

                BindProductVariantAttributes();
            }
        }

        protected void gvProductVariantAttributes_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ProductVariantAttribute productVariantAttribute = (ProductVariantAttribute)e.Row.DataItem;

                Button btnUpdate = e.Row.FindControl("btnUpdate") as Button;
                if (btnUpdate != null)
                    btnUpdate.CommandArgument = e.Row.RowIndex.ToString();

                DropDownList ddlProductAttribute = e.Row.FindControl("ddlProductAttribute") as DropDownList;
                ddlProductAttribute.Items.Clear();
                ProductAttributeCollection productAttributes = ProductAttributeManager.GetAllProductAttributes();
                foreach (ProductAttribute productAttribute in productAttributes)
                {
                    ListItem item = new ListItem(productAttribute.Name, productAttribute.ProductAttributeID.ToString());
                    ddlProductAttribute.Items.Add(item);
                    if (productAttribute.ProductAttributeID == productVariantAttribute.ProductAttributeID)
                        item.Selected = true;
                }
            }
        }

        protected void gvProductVariantAttributes_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int productVariantAttributeID = (int)gvProductVariantAttributes.DataKeys[e.RowIndex]["ProductVariantAttributeID"];
            ProductVariantAttributeManager.DeleteProductVariantAttribute(productVariantAttributeID);
            BindProductVariantAttributes();
        }

        public int ProductVariantID
        {
            get
            {
                return CommonHelper.QueryStringInt("ProductVariantID");
            }
        }
    }
}